function [ Results ] = MyTsls( Y , X , IV , W )

% Need to include exogenous X in instruments
% Observations are columns

% Define weights
switch nargin
    case 3
        w = ones( size( Y , 1 ) ) ;
    case 4
        w = W ;
    otherwise
        error('Wrong number of arguments')
end
w = w / sum(w) ;

% Remove infs and nans
drop = (   isnan( Y ) + sum( isnan( X ) , 2 ) + sum( isnan( IV ) , 2 ) + sum( isnan( w ) , 2 ) ...
         + isinf( Y ) + sum( isinf( X ) , 2 ) + sum( isinf( IV ) , 2 ) + sum( isinf( w ) , 2 ) ...
       ) > 0 ;
   
Y(drop,:) = [] ;
X(drop,:) = [] ;
IV(drop,:) = [] ;
w(drop,:) = [] ;

% First stage
Nx = size(X,2) ;
for i=1:Nx
    FS{i} = fitlm( IV , X(:,i) , 'Weights', w ) ;
    Predict(:,i) = predict( FS{i} , IV ) ;
end

% Second stage
Results = fitlm( Predict ,  Y , 'Weights', w ) ;
  

end

